from django.shortcuts import render,reverse
from django.http import HttpResponse
from .. import models
from django.core.urlresolvers import reverse
from .views_index import uploads
from myweb.settings import BASE_DIR
import os

# Create your views here.

# 商品添加
def goodsadd(request):
    if request.method == 'GET':
        # 获取所有商品分类
        data = models.category.objects.extra(select={'paths': 'concat(path,id)'}).order_by('paths')
        # 分配数据
        context = {'categorylist': data}
        # 加载添加页面
        return render(request,'myadmin/goods/add.html',context)
    elif request.method == 'POST':
        try:
            # 接收数据
            data = request.POST.dict()
            data.pop('csrfmiddlewaretoken')
            data['category_id'] = models.category.objects.get(id= data['category_id'])
            # 保存上传主图片
            goodspic = request.FILES.get('pic_url')
            # 判断是否上传了主图片
            if goodspic:
                data['pic_url'] = uploads(goodspic)
            else:
                return HttpResponse('<script>alert("必须上传商品主图片")</script>')

            # 添加保存数据
            ob = models.goods(**data)
            ob.save()
            return HttpResponse('<script>alert("添加成功");location.href="' + reverse('myadmin_goods_index') + '"</script>')
        except:
            return HttpResponse('<script>alert("添加失败");location.href="' + reverse('myadmin_goods_add') + '"</script>')


# 商品列表页
def goodsindex(request):
    # 获取商品数据
    data = models.goods.objects.all()
    # 获取搜索条件和参数
    types = request.GET.get('types')
    keywords = request.GET.get('keywords')
    # 判断是否有搜索条件
    if types:
        # 按商品名称搜索
        if types == 'name':
            data = data.filter(name__contains=keywords)

        # 按商品价格搜索
        if types == 'price':
            arr = keywords.split(',')
            data = data.filter(price__gte=arr[0]).filter(price__lte=arr[1])
        if types=='status':
            # 状态  0:新发布 1:热卖 2:下架  3:打折
            if keywords=='新发布':
                data = data.filter(status=0)
            elif keywords=='热卖':
                data = data.filter(status=1)
            elif keywords == '下架':
                data = data.filter(status=2)
            elif keywords == '打折':
                data = data.filter(status=3)

    # 数据分页
    from django.core.paginator import Paginator

    # 实例化分页类 参数1,获取的所有的数据对象   参数2 每页显示多少条
    paginator = Paginator(data, 8)

    # 获取当前页码数  ?p=n
    p = request.GET.get('p',1)

    # 获取当前页的数据
    goodslist = paginator.page(p)

    # 分配数据
    context = {'goodslist':goodslist}
    return render(request,'myadmin/goods/index.html',context)


# 商品修改
def goodsedit(request,gid):
    # 获取所有商品分类
    cate = models.category.objects.extra(select={'paths': 'concat(path,id)'}).order_by('paths')
    # 根据请求获取对应商品对象
    ob = models.goods.objects.get(id=gid)
    # 判断请求方式
    if request.method == 'GET':
        # 加载修改页面
        return render(request,'myadmin/goods/edit.html',{'goodinfo':ob,'catelist':cate})
    elif request.method == 'POST':
        try:
            # 获取修改数据
            data = request.POST.dict()
            data.pop('csrfmiddlewaretoken')
            print(data)
            # 判断主图是否修改
            goodspic = request.FILES.get('pic_url')
            # 判断是否上传了主图片
            if goodspic:
                try:
                    # 删除原文件
                    os.remove(BASE_DIR + ob.pic_url)

                except:
                    pass
                # 保存上传图片
                ob.pic_url = uploads(goodspic)
            ob.name = data['name']
            ob.price = data['price']
            ob.store = data['store']
            ob.info = data['info']
            ob.save()
            return HttpResponse('<script>alert("修改成功");location.href="' + reverse('myadmin_goods_index') + '"</script>')
        except:
            return HttpResponse('<script>alert("修改失败");location.href="' + reverse('myadmin_goods_edit') + '"</script>')

# 商品删除
def goodsdel(request,gid):
    try:
        # 根据请求获取对应商品对象
        ob = models.goods.objects.get(id=gid)
        ob.delete()
        return HttpResponse('<script>alert("删除成功");location.href="' + reverse('myadmin_goods_index') + '"</script>')
    except:
        return HttpResponse('<script>alert("删除失败");location.href="' + reverse('myadmin_goods_index') + '"</script>')
